/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class FileManagerActions extends com.servengine.struts.ClientAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( FileManagerActions.class.getName() );
	public void initAction(javax.naming.Context context)
	{
		log.info(getClass().getName()+" initialized");
	}
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		return mapping.findForward("success");
	}

	public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
		  File c = filemanageractionform.isSearchfullfilemanager()?filemanageractionform.getRoot():filemanageractionform.getCurrent();
		  filemanageractionform.setFoundfiles(findDir(c,filemanageractionform.getSearchstring(),new ArrayList<FileManagerElement>()));
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}

	private ArrayList<FileManagerElement> findDir(File dir, String name, ArrayList<FileManagerElement> ar)
	{
		for(String entry: dir.list())
		{
			FileManagerElement f = new FileManagerElement(dir.getAbsolutePath(),entry);
			if (f.isDirectory())
				ar = findDir(f,name,ar);
			else if (f.getName().indexOf(name)>-1) 
				ar.add(f);
		}
		return ar;
	}
	public ActionForward getEditfile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
		  response.setContentType(servletcontext.getMimeType(filemanageractionform.getEditfilename())); 
		  response.setHeader("Content-disposition", "attachment;filename="+filemanageractionform.getEditfilename());     
		  FileInputStream fis = new FileInputStream(filemanageractionform.getEditfile());
			OutputStream os = response.getOutputStream();
		  byte[] buf = new byte[1024];
		  int a = 0;
		  while((a=fis.read(buf))!=-1)
		    os.write(buf, 0, a);
		  fis.close();
		  os.close();
		  return null;
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
	}
	public ActionForward renameEditfile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
			filemanageractionform.setEditfilename(filemanageractionform.getFilenameargument());
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}
	public ActionForward mkdir(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
			new File(filemanageractionform.getCurrent(),filemanageractionform.getFilenameargument()).mkdir();
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}
	public ActionForward mkdirs(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
		  new File(filemanageractionform.getCurrent(),filemanageractionform.getFilenameargument()).mkdir();
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
	  return mapping.findForward("success");
	}
	public ActionForward storeFormfile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
		  FileOutputStream fos = new FileOutputStream(new File(filemanageractionform.getCurrent(), filemanageractionform.getFormfile().getFileName()));
			InputStream is = filemanageractionform.getFormfile().getInputStream();
		  byte[] buf = new byte[1024];
		  int a = 0;
		  while((a=is.read(buf))!=-1)
		    fos.write(buf, 0, a);
		  is.close();
		  fos.close();
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}
	protected void initFileManager(FileManagerActionForm filemanager, String path, boolean create, long maxfilesize,long maxspace)
	{
		filemanager.initFilemanager(path,create,maxfilesize,maxspace);
	}
	public ActionForward removeFiles(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		FileManagerActionForm filemanageractionform = (FileManagerActionForm)form;
		try
		{
			if (filemanageractionform.getRemoveFiles()!=null)
				for (String filename: filemanageractionform.getRemoveFiles())
					new com.servengine.util.File(filemanageractionform.getCurrent()).deleteAll(filename);
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			ActionErrors errors = new ActionErrors();
			errors.add("error",new ActionMessage(e.getClass().getName(),e.getMessage()));
			saveErrors(request,errors);
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}
}
